import { Input, Tag, Modal, Table } from "antd";
import { SelectOutlined } from '@ant-design/icons';
import { useEffect, useState } from "react";
import SearchForm from "@/components/searchForm";
import DisplayLabel from "@/components/displayLabel";
import { useQuery, keepPreviousData } from "@tanstack/react-query";
import { dataSourcePage, dataSourceAllList } from '@/api/sharing/dataSource'


const queryItems = [
  {
    name: 'keyword',
    label: '数据源名称',
    type: 'INPUT',
  },
  {
    name: 'dataSourceType',
    label: '数据源类型',
    type: 'SELECT',
    dictType: 'data_source_type'
  }
];
const DataSourceSelect = ({ value, onChange, id, placeholder }) => {
  const [showValue, setShowValue] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [selectedKeys, setSelectedKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [queryParam, setQueryParam] = useState({});
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['DataSourceSelect-dataSourcePage', queryParam, page],
    queryFn: () => {
      return dataSourcePage({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam,
      }).then((res) => {
        return res.result || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
    enabled: isModalOpen,
  })

  const { data: sourceAllList } = useQuery({
    queryKey: ['DataSourceSelect-dataSourceAllList', queryParam, page],
    queryFn: () => {
      return dataSourceAllList({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam,
      }).then((res) => {
        return res.result || {}
      })
    },
    placeholderData: keepPreviousData,
  })

  const columns = [
    {
      title: '数据源名称',
      dataIndex: 'dataSourceName',
    },
    {
      title: '数据源类型',
      dataIndex: 'dataSourceType',
      render: (text) => (<Tag><DisplayLabel value={text} type="data_source_type" /></Tag>)
    },
    {
      title: '数据库名',
      dataIndex: 'databaseName',
    },
    {
      title: '描述',
      dataIndex: 'describe',
    },
  ];

  const showSelect = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false)
    onChange(selectedKeys[0])
  };
  const handleCancel = () => {
    setIsModalOpen(false)
  };

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
    // setShowValue(selectedRows[0]?.dataSourceName)
  }

  useEffect(() => {
    setShowValue(sourceAllList?.find(d => d.id === value)?.dataSourceName)
  }, [value, sourceAllList])

  return (<>
    <Input
      id={id}
      value={showValue || value}
      readOnly
      onClick={showSelect}
      placeholder={placeholder}
      suffix={
        <SelectOutlined />
      }
    />

    <Modal width={'70%'} title="数据源选择" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
            setQueryParam({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        searchContent="查询"
        showReset={false}
      />
      <div style={{ marginTop: '20px' }}>
        <Table
          rowSelection={{ type: 'radio', selectedRowKeys: selectedKeys, onChange: onSelectChange }}
          columns={columns}
          rowKey={(record) => record.id}
          loading={isFetching}
          dataSource={tableData?.records}
          pagination={{
            current: page.pageNo,
            pageSize: page.pageSize,
            total: tableData?.total,
            onChange: (pageNo, pageSize) => {
              setPage({ pageNo, pageSize })
            }
          }}
        />
      </div>
    </Modal>
  </>);
}
export default DataSourceSelect;